package com.mapler.tbot.service;

import com.mapler.ngfx.service.*;
import com.mapler.model.SModel;
import com.mapler.model.UAModel;
import com.mapler.service.INotifier;
import com.mapler.service.MailRunner;
import com.mapler.utility.Util;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;

/**
 *
 * @author none
 */
public class TBotClick implements Runnable {

    private SModel sModel;
    private static Logger log = Logger.getLogger(NGFXSignupClick.class);
    private INotifier iNotifier;
    private UAModel uAModel = new UAModel();
    
    public TBotClick(INotifier iNotifier, SModel sModel) {
        this.sModel = sModel;
        this.iNotifier = iNotifier;
    }

    public TBotClick(SModel iModel) {
        this.sModel = iModel;
    }

    @Override
    public void run() {
        try {
            if (sModel.isIsVPN()) {
                log.debug("TBot:Run::Going to run for VPN");
                if (sModel.getLinks().isEmpty() || sModel.getProxyes().isEmpty()
                        || sModel.getName().isEmpty() || sModel.getPass().isEmpty()) {
                    iNotifier.notify("TBot:: Stop working link, proxy, username or password is empty");
                    log.debug("TBot:: Stop working link, proxy, username or password is empty");
                    return;
                }
                this.init();
                log.debug("TBot:Run::Done !!!");
            } else {
                log.debug("TBot:Run::Going to run for SOCKS");
                this.init();
                log.debug("TBot:Run::Done !!!");
            }
        } catch (Throwable ex) {
            iNotifier.notify("TBot:Run:: stopped for error: " + ex.getMessage());
            log.error("TBot:Run:: stopped causes " + ex);
        }
    }

    private void init() {

        for (int i = 0;; i++) {
            try {
                if (sModel.isStopEngine()) {
                    break;
                }
                 String proxy = "";
                if (sModel.isIsVPN()) {
                     int index = Util.getRandom().nextInt(sModel.getProxyes().size());
                     proxy = sModel.getProxyes().get(index);
                
                    iNotifier.notify("TBot:: Going to connect VPN for " + proxy);
                    boolean connect = Util.connect(proxy, sModel.getName(), sModel.getPass());
                    if (!connect) {
                        iNotifier.notify("TBot:: unable to connect VPN.");
                        log.debug("TBot:: unable to connect for " + proxy);
                        continue;
                    }
                }

                this.doPost();
                
                if (sModel.isIsVPN()) {
                    boolean disconnect = Util.disConnect(proxy, sModel.getName(), sModel.getPass());
                    if (!disconnect) {
                        iNotifier.notify("TBot:: unable to disconnec VPN ");
                        log.debug("TBot:: unable to disconnect VPN(no more further action) for " + sModel.getProxy());
                        break;
                    } else {
                        iNotifier.notify("TBot:: disconnected from VPN ");
                        log.debug("TBot:: disconnected form VPN ");
                    }
                }

                iNotifier.notify("Tbot:: Waiting 1 sec for before another post.");
                Util.wait(1);

            } catch (Throwable ex) {
                iNotifier.notify("Signup::Critical error on signup. No more work..." + ex.getMessage());
                log.debug("Signup::Critical error on signup. No more work..." + ex);
            }
        }
        iNotifier.notify("Signup:: Finished work !!! ");
        log.debug("Signup:: Finished work !!! ");
    }

    private void doPost() {
        WebDriver driver = null;
        try {
            driver = Util.createDriver(sModel,uAModel);
            if (driver == null) {
                iNotifier.notify("Tbot:: unable to init driver. driver is null");
                log.debug("Tbot:: driver is null. Unable to init driver");
                throw new Exception("Tbot:: driver is null. Unable to init driver");
            }

            long time1 = System.currentTimeMillis() / 1000;
            TimeoutThread timeoutThread = new TimeoutThread(Integer.parseInt(sModel.getMaxWaitTime()));
            timeoutThread.start();
            
            int index = Util.getRandom().nextInt(sModel.getLinks().size());
            String link = sModel.getLinks().get(index);                     
            driver.get(link);
            
            timeoutThread.interrupt();
            Throwable e = ThreadReturn.get(timeoutThread.getName());
            if (e != null) {
                System.out.println("Timed out: " + e.getMessage());
            } else {
                System.out.println("No timeout");
            }

            if (!sModel.isCloseJustAfterLoad()) {
                long time2 = System.currentTimeMillis() / 1000;

                long timeDiff = time2 - time1;
                long maxWaitTime = Long.parseLong(sModel.getMaxWaitTime());
                if (timeDiff < maxWaitTime) {
                    int timeLeft = (int) (maxWaitTime - timeDiff);
                    Util.wait(timeLeft);
                }
            }

        } catch (Throwable ex) {
            //iNotifier.notify("Tbot:: Stopped for error: " + ex.getMessage());
            log.error("Tbot:: Stopped causes..." + ex);
            ex.printStackTrace();
        } finally {
            if (driver != null) {
                driver.close();
            }
        }
    }

    public static void main(String s[]) {
        SModel sModel = new SModel();
        sModel.setDriver("FF");
        sModel.setLink("http://google.com/");
        sModel.setMaxWaitTime("1");
        TBotClick click = new TBotClick(sModel);

        click.doPost();
        //click.doIT();

    }

    private void doIT() {
        SModel sModel = new SModel();
        sModel.setDriver("FF");
        sModel.setLink("http://nigeria-forex.com/forum.php?referrerid=27246");
        sModel.setUseFWlink("0");
        sModel.setUsername("mithun");
        sModel.setPassword("mithun");
        NGFXSignupClick click = new NGFXSignupClick(sModel);
        UAModel model = new UAModel();
        model.setEmail("skyroproject8@gmail.com");
        model.setEmailPassword("mn142536");
        model.setUsername("prantoor");
        model.setPassword("pass123");
        model.setId("22");
        MailRunner mailRunner = new MailRunner(iNotifier, sModel, model);
        mailRunner.checkNGFXEmail(null);
    }
}